<template>
  <div class="customer-container">
    <h3 class="page-title">新增客户</h3>

    <!-- 客户基本信息表单 -->
    <el-form :model="customerForm" label-width="380px" class="base-form">
      <div class="form-row">
        <el-form-item label="客户编号">
          <el-input v-model="customerForm.customernumber" disabled></el-input>
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="customerForm.CustomerName"></el-input>
        </el-form-item>
      </div>

      <div class="form-row">
        <el-form-item label="传真">
          <el-input v-model="customerForm.fax"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="customerForm.phone"></el-input>
        </el-form-item>
      </div>

      <div class="form-row">
        <el-form-item label="邮箱">
          <el-input v-model="customerForm.email"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="customerForm.remarks"></el-input>
        </el-form-item>
      </div>
    </el-form>

    <!-- 联系人表格 -->
    <el-table :data="AddConact" style="width: 1080px; margin-top: 20px">
      <el-table-column prop="contactPerson" label="联系人" width="120">
        <template #default="{ row }">
          <el-input v-model="row.contactPerson" placeholder="请输入"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="地址" width="120">
        <template #default="{ row }">
          <el-input v-model="row.address" placeholder="请输入"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="contactPhone" label="电话" width="120">
        <template #default="{ row }">
          <el-input v-model="row.contactPhone" placeholder="请输入"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="creationTime" label="创建时间" width="120">
        <template #default="{ row }">
          <el-input v-model="row.creationTime" placeholder="请输入"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220">
        <el-form-item>
          <el-button size="mini" type="danger" @click="removeContact(index)"
            >删除</el-button
          >
        </el-form-item>
      </el-table-column>
    </el-table>

    <!-- 操作按钮 -->
    <div class="button-group" style="text-align: right; margin-top: 20px">
      <el-button @click="addContact()">新增联系人</el-button>
      <el-button type="primary" @click="handleBatchAdd()">确定</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessageBox, ElTable, ElMessage } from "element-plus";
import { reactive, onMounted, ref } from "vue";
import axios from "axios";
import { Plus } from "@element-plus/icons-vue";
import { useRouter, useRoute } from "vue-router";
import dayjs from "dayjs";
import { KongaUrl } from "@/axios/axiosHelp";
const router = useRouter();
const route = useRoute();
const AddConact = ref([]); // 明确类型定义

interface ContactItem {
  contactId: number;
  customerId: string;
  contactPerson: string;
  address: string;
  contactPhone: string;
  creationTime: string; // 注意字段命名统一
  isDelete: boolean;
}

// 修改2：优化customerForm结构
interface CustomerForm {
  customerId: string;
  customernumber: string;
  CustomerName: string;
  fax: string;
  phone: string;
  email: string;
  remarks: string;
}

const customerForm = ref<CustomerForm>({
  customerId: "",
  customernumber: "",
  CustomerName: "",
  fax: "",
  phone: "",
  email: "",
  remarks: "",
});

// 修改3：优化handleEdit异步处理
const handleEdit = async () => {
  const customerId = route.query.customerId as string;
  if (!customerId) {
    console.log("未获取到客户ID");
    return;
  }

  try {
    // 获取客户基本信息
    const [basicRes, contactRes] = await Promise.all([
    KongaUrl.get(`/wangcong/api/Whouase/EditCustomer`, {
        params: { CustomerId: customerId },
      }),
      KongaUrl.get(`/wangcong/api/Whouase/EditContact`, {
        params: { CustomerId: customerId },
      }),
    ]);

    // 处理基础信息
    if (basicRes.data.data?.length > 0) {
      const basicInfo = basicRes.data.data[0];
      customerForm.value = {
        ...customerForm.value,
        ...basicInfo,
        // 确保字段映射正确
        Customernumber: basicInfo.customerNumber || "", // 注意后端字段名
        CustomerName: basicInfo.customerName || "",
        // 其他字段...
      };
    }

    // 处理联系人信息
    if (contactRes.data.data) {
      AddConact.value = contactRes.data.data.map((item) => ({
        contactId: item.contactId, // 确保后端字段名一致
        customerId: customerId,
        contactPerson: item.contactPerson, // 而不是ContactPerson
        address: item.address,
        contactPhone: item.contactPhone,
        creationTime: dayjs(item.creationTime).toISOString(), // 统一使用ISO格式
        isDelete: item.isDelete,
      }));
    }
  } catch (error) {
    console.error("数据获取失败:", error);
    ElMessage.error("数据加载失败");
  }
};
const addContact = () => {
  customerForm.value.contacts.push(createEmptyContact());
};
// 创建空联系人模板
function createEmptyContact() {
  return {
    contactId: 0,
    contactPerson: "",
    address: "",
    contactPhone: "",
    creationTime: dayjs().format("YYYY-MM-DDTHH:mm:ss"), // 格式化日期时间
    isDelete: false,
  };
}

const removeContact = (index) => {
  ElMessageBox.confirm("是否确认删除?", "提示", {
    confirmButtonText: "是",
    cancelButtonText: "否",
    type: "warning",
  }).then(() => {
    customerForm.value.contacts.splice(index, 1);
  });
};
const handleBatchAdd = async () => {
  const payload = {
    ...customerForm.value,
    customerId: AddConact.value[0]?.customerId || 0, // 主表ID
    contacts: AddConact.value.map((item) => ({
      contactId: item.contactId,
      customerId: item.customerId,
      contactPerson: item.contactPerson,
      address: item.address,
      contactPhone: item.contactPhone,
      creationTime: item.creationTime,
      isDelete: item.isDelete,
    })),
  };

  try {
    const res = await KongaUrl.post(
      "/wangcong1/api/WHouase/UpdateCustomer",
      payload
    );
    if (res.data.code === 300) {
      ElMessage.success("修改成功");
      router.push("/GetCustomer");
    } else {
      ElMessage.error(res.data.message);
    }
  } catch (error) {
    ElMessage.error("请求失败，请检查控制台");
    console.error("API Error:", error);
  }
};
// const handleBatchAdd = async () => {
//   try {
//     // 调用API
//     const response = await axios.post(
//       "https://localhost:7193/api/WHouase/AddContactsWithCustomer",
//       customerForm
//     );

//     if (response.data.code === 200) {
//       ElMessage.success("添加成功");
//       // 重置表单
//     } else {
//       ElMessage.error(response.data.message);
//     }
//   } catch (error) {
//     ElMessage.error("请求失败: ");
//   }
// };

const generateTwelveDigitNumber = () => {
  const characters = "0123456789";
  let result = "";
  for (let i = 0; i < 6; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
};

// 提交
onMounted(() => {
  //   customerForm.value.Customernumber = generateTwelveDigitNumber();
  handleEdit();
});
</script>

<style scoped>
.customer-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.page-title {
  margin-bottom: 20px;
  font-size: 18px;
  color: #606266;
}

.base-form {
  background: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-row {
  display: flex;
  margin-bottom: 15px;

  margin-bottom: 0;
}

.form-row > .el-form-item {
  flex: 1;
  margin-right: 20px;
  margin-right: 0;
}

.button-group {
  margin-top: 20px;
}
</style>